<?php

include_once 'Repost.php';
include_once 'PostDAO.php';
include_once 'DBConnection.php';

class RepostDAO {
	
	private static $instance;	
	
	private function __construct() {
		
	}
	
	public static function getInstance() {
		if (!isset(self::$instance)) {
			$className = __CLASS__;
			self::$instance = new $className;
		}
		return self::$instance;
	}
	
	public function addRepost($repost) {
		if ($repost instanceof Repost) {
			$db=DBConnection::getInstance();								
			if ($db instanceof DBConnection) {				
				try {
					$dbh = $db->getDBH();
					$smt = $dbh->prepare(Repost::addRepostStatement());
					$smt->execute(array($repost->getPrevPost(), $repost->getDisplayedPost(), $repost->getOriginalPost()));
					return $dbh->lastInsertId();
				} catch (PDOException $e) {
					echo "Error: ".$e->getMessage()."<br />";
				}			
			}		
		}
	}
	
	public function repost($userId, $postId) {		
		$db=DBConnection::getInstance();
		$postdao=PostDAO::getInstance();
		if (($db instanceof DBConnection) && ($postdao instanceof PostDAO)) {
			$opid=$postdao->getOriginalPostIdtByPostId($postId);
			$tags=$postdao->getTagsByPostId($postId);
			
			$repost = new Repost();
			$repost->setOriginalPost($opid);
			$repost->setPrevPost($postId);
			$repost->setUserId($userId);
			$repost->setDsiplayedPost(null);
			$dbh = $db->getDBH();
			try{
				$dbh->beginTransaction();	
				$smt = $dbh->prepare(Repost::addRepostStatement());
				$smt->execute(array($repost->getPrevPost(), $repost->getDisplayedPost(), $repost->getOriginalPost()));
				//$rid = $this->addRepost($repost);
				//echo $rid;
				$stmt = $dbh->prepare(
					'INSERT INTO post VALUES(DEFAULT, ?, NULL, LAST_INSERT_ID(), DEFAULT)'
				);
				$stmt->execute(	array($userId) );
				$dbh->commit();
			} catch (Exception $e) {
				$dbh->rollBack();
				echo "Failed: " . $e->getMessage() . "<br />";
			}
		}
	}
	
}

?>